﻿$(function () {

});
function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds) {
            break;
        }
    }
}
var file_type = "";
function readURL(input) {

    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            var split = e.target.result.toString().split("/");
            file_type = split[0];
            if (file_type == "data:image") {
                $('#img_review').attr('src', e.target.result);
                document.getElementById("img_review").style.display = "block";
            }
            else {
                document.getElementById("img_review").style.display = "none";
            }
        }

        reader.readAsDataURL(input.files[0]);
    }
}
function sapxepdanhmuc() {
    document.getElementById('sapxepdanhmuc').style.display = 'block'
}
function themdanhmuc() {
    document.getElementById('themdanhmuc').style.display = 'block'
}
function suadanhmuc() {
    document.getElementById("txt_edit_category").value = $("#danhmuc").find(":selected").text();
    document.getElementById('suadanhmuc').style.display = 'block'
}
function xoadanhmuc() {
    var id = document.getElementById("danhmuc").value;
    document.getElementById('xoadanhmuc').style.display = 'block'
    document.getElementById("txt_del_cate_id").innerHTML = id;
}
function xoabaiviet(id) {
    document.getElementById("del_news_id").innerHTML = id;
    document.getElementById('xoabaiviet').style.display = 'block'
}

function thembaiviet() {
    document.getElementById("sua-bai-viet").style.display = "none";
    document.getElementById("them-bai-viet").style.display = "block";
    var newslinks = document.getElementsByClassName("newslinks");
    for (var j = 0; j < newslinks.length; j++) {
        newslinks[j].className = newslinks[j].className.replace(" w3-leftbar w3-border-teal", "");
    }
}
function suabaiviet(id) {
    $(document).ready(function () {
        document.getElementById("news_detail_area").style.display = "block";
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("news_detail_area").innerHTML = xhttp.responseText;
                $("#img_add_news").on("change", function () {
                    readURL(this);
                });
                $("#btn_edited_news").click(function () {
                    var cate_id = document.getElementById("danhmuc").value;
                    var news_id = document.getElementById("edit_news_id").innerHTML;
                    var cate = document.getElementById("edit_category").value;
                    var title = $("#txt_edit_title").val();
                    var review = $("#txt_edit_review").val();
                    var content = tinyMCE.get("txt_news_content").getContent();
                    var source = document.getElementById("txt_edit_source").value;
                    var tags = document.getElementById("txt_edit_tag").value;
                    var img = document.getElementById("img_add_news").value;
                    var show = "0";
                    var top = "0";
                    var newslinks = document.getElementsByClassName("newslinks");
                    for (var j = 0; j < newslinks.length; j++) {
                        newslinks[j].className = newslinks[j].className.replace(" w3-leftbar w3-border-teal", "");
                    }
                    if ($("#show-edit").is(":checked"))
                        show = "1";
                    if ($("#top-edit").is(":checked"))
                        top = "1";
                    if (title.trim().length < 10) {
                        document.getElementById("error-modal").style.display = "block";
                        document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Tiêu đề phải tối thiểu 10 ký tự";
                        setTimeout("$('#error-modal').fadeOut()", 2000);
                    }
                    else {
                        if (review.trim().length < 20) {
                            document.getElementById("error-modal").style.display = "block";
                            document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Lời dẫn phải tối thiểu 20 ký tự";
                            setTimeout("$('#error-modal').fadeOut()", 2000);
                        }
                        else {
                            if (img != "") {
                                if (file_type != "data:image") {
                                    document.getElementById("error-modal").style.display = "block";
                                    document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Tệp đã chọn không phải là hình ảnh";
                                    setTimeout("$('#error-modal').fadeOut()", 2000);
                                }
                                else {
                                    var file_data = document.getElementById('img_add_news').files[0];
                                    if (file_data == null) return; // chưa chọn file
                                    var form_data = new FormData();
                                    form_data.append("img_add_news", file_data);
                                    $.ajax({
                                        url: '../ajax/asp/news/upload_avatar.aspx',
                                        data: form_data,
                                        processData: false,
                                        contentType: false,
                                        type: 'POST',
                                        success: function (data) {
                                            //$("#divTreeView").html(data);
                                        }
                                    });
                                    sleep(5000);
                                }
                            }
                            $.post("../ajax/asp/news/edited_News_detail.aspx", { "id": news_id, "cate": cate, "title": title.trim(), "review": review.trim(), "content": content.trim(), "source": source.trim(), "tags": tags.trim(), "img": img, "show": show, "top": top });

                            if (cate != cate_id) {
                                $(".news" + news_id).remove();
                            }
                            else {
                                if (top == "1" && show == "1") {
                                    document.getElementsByClassName("news" + news_id)[0].innerHTML = "<div class='w3-col l10'>" + title.trim() + "</div><div class='w3-center w3-col l1 w3-right'><i class='fa fa-star w3-large w3-text-red'></i></div><div class='w3-center w3-col l1 w3-right'><i class='fa fa-eye w3-large w3-text-orange'></i>&nbsp;</div>";
                                }
                                else {
                                    if (top == "1" && show == "0")
                                        document.getElementsByClassName("news" + news_id)[0].innerHTML = "<div class='w3-col l10'>" + title.trim() + "</div><div class='w3-center w3-col l1 w3-right'><i class='fa fa-star w3-large w3-text-red'></i></div><div class='w3-center w3-col l1 w3-right'>&nbsp;</div>";
                                    else {
                                        if (top == "0" && show == "1")
                                            document.getElementsByClassName("news" + news_id)[0].innerHTML = "<div class='w3-col l10'>" + title.trim() + "</div><div class='w3-center w3-col l1 w3-right'>&nbsp;</div><div class='w3-center w3-col l1 w3-right'><i class='fa fa-eye w3-large w3-text-orange'></i>&nbsp;</div>";
                                        else {
                                            if(top=="0"&&show=="0")
                                                document.getElementsByClassName("news" + news_id)[0].innerHTML = "<div class='w3-col l10'>" + title.trim() + "</div><div class='w3-center w3-col l1 w3-right'>&nbsp;</div><div class='w3-center w3-col l1 w3-right'>&nbsp;</div>";
                                        }
                                    }
                                }
                                    
                            }

                            document.getElementById("success-modal").style.display = "block";
                            document.getElementById("success-modal").getElementsByClassName("success_content")[0].innerHTML = "Đã lưu thành công";
                            setTimeout("$('#success-modal').fadeOut()", 2000);
                            document.getElementById("news_detail_area").style.display = "none";

                        }
                    }

                });

                $("#btn_reup_news").click(function () {
                    var news_id = document.getElementById("edit_news_id").innerHTML;
                    $.post("../ajax/asp/news/reup_news.aspx", { "id": news_id });

                    document.getElementById("success-modal").style.display = "block";
                    document.getElementById("success-modal").getElementsByClassName("success_content")[0].innerHTML = "Đăng lại thành công";
                    setTimeout("$('#success-modal').fadeOut()", 2000);
                });
                //tiny-mce
                tinymce.remove('textarea');
                tinymce.init({
                    selector: 'textarea#txt_news_content',
                    height: 180,
                    width: '83%',
                    plugins: [
                      'advlist autolink lists link image charmap print preview anchor',
                      'searchreplace visualblocks code fullscreen furigana ',
                      'insertdatetime media table contextmenu paste code',
                      'textcolor'
                    ],
                    fontsize_formats: "8px 10px 12px 14px 15px 16px 18px 20px 21px 22px",
                    toolbar: 'fontsizeselect insertfile undo redo | styleselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image furigana'

                });
            }
        };
        xhttp.open("GET", "../ajax/asp/news/edit_news_detail.aspx?id=" + id, true);
        xhttp.send();
    });
}

function sort_cate() {
    var z = "";
    var l = document.getElementById("sortable").getElementsByClassName("ui-state-default").length;
    for (var i = 0; i < l; i++) {
        if (i != 0)
            z += ",";
        z += document.getElementById("sortable").getElementsByClassName("ui-state-default")[i].getElementsByClassName("cate_id")[0].innerHTML;
    }
    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (xhttp.readyState == 4 && xhttp.status == 200) {
            location.reload(true);
        }
    };
    xhttp.open("GET", "../ajax/asp/news/change_index_cate.aspx?index=" + z, true);
    xhttp.send();
    
}
$(document).ready(function () {

    $("#danhmuc").on("change", function () {
        var id = document.getElementById("danhmuc").value;
        document.getElementById("news_detail_area").style.display = "none";
        if (id != 0) {
            var xhttp;
            xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function () {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    document.getElementById("news_area").innerHTML = xhttp.responseText;
                    $(".newslinks").click(function () {
                        var newslinks = document.getElementsByClassName("newslinks");
                        for (var j = 0; j < newslinks.length; j++) {
                            newslinks[j].className = newslinks[j].className.replace(" w3-leftbar w3-border-teal", "");
                        }
                        $(this).addClass(" w3-leftbar w3-border-teal");
                    });
                }
            };
            xhttp.open("GET", "../ajax/asp/news/get_news.aspx?id=" + id, true);
            xhttp.send();
            document.getElementById("btn_Edit_Category").style.display = "inline-block";
            document.getElementById("Add_News").style.display = "block";

            document.getElementById("news_area").style.display = "block";
        }
        else {
            document.getElementById("btn_Edit_Category").style.display = "none";
            document.getElementById("Add_News").style.display = "none";

            document.getElementById("news_area").style.display = "none";
        }
    });
    $("#btn_new_category").click(function () {
        var name = document.getElementById("txt_new_category").value;
        $.post("../ajax/asp/news/add_category.aspx", { "name": name.trim() });
        location.reload(true);
    });
    $("#btn_edit_category").click(function () {
        var id = document.getElementById("danhmuc").value;
        var name = document.getElementById("txt_edit_category").value;
        $.post("../ajax/asp/news/edit_category.aspx", { "id": id, "name": name.trim() });
        location.reload(true);
    });
    $(".btn_del_category").click(function () {
        var id = document.getElementById("danhmuc").value;
        $.post("../ajax/asp/news/del_category.aspx", { "id": id});
        location.reload(true);
    });


    $("#btn_add_news").click(function () {
        document.getElementById("news_detail_area").style.display = "block";
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function () {
            if (xhttp.readyState == 4 && xhttp.status == 200) {
                document.getElementById("news_detail_area").innerHTML = xhttp.responseText;
                $("#img_add_news").on("change", function () {
                    readURL(this);
                });
                $("#btn_add_news_detail").click(function () {
                    var cate = document.getElementById("danhmuc").value;
                    var title = $("#txt_add_news_title").val();
                    var review = $("#txt_add_news_review").val();
                    var content = tinyMCE.get("txt_news_content").getContent();
                    var source = document.getElementById("txt_add_news_source").value;
                    var tags = document.getElementById("txt_add_news_tags").value;
                    var img = document.getElementById("img_add_news").value;
                    var show = "0";
                    var top = "0";
                    var newslinks = document.getElementsByClassName("newslinks");
                    for (var j = 0; j < newslinks.length; j++) {
                        newslinks[j].className = newslinks[j].className.replace(" w3-leftbar w3-border-teal", "");
                    }
                    if ($("#show-create").is(":checked"))
                        show = "1";
                    if ($("#top-create").is(":checked"))
                        top = "1";
                    if (title.trim().length < 10) {
                        document.getElementById("error-modal").style.display = "block";
                        document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Tiêu đề phải tối thiểu 10 ký tự";
                        setTimeout("$('#error-modal').fadeOut()", 2000);
                    }
                    else {
                        if (review.trim().length < 20) {
                            document.getElementById("error-modal").style.display = "block";
                            document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Lời dẫn phải tối thiểu 20 ký tự";
                            setTimeout("$('#error-modal').fadeOut()", 2000);
                        }
                        else {
                            if (img == "") {
                                document.getElementById("error-modal").style.display = "block";
                                document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Ảnh bìa không được để trống";
                                setTimeout("$('#error-modal').fadeOut()", 2000);
                            }
                            else {
                                if (file_type != "data:image") {
                                    document.getElementById("error-modal").style.display = "block";
                                    document.getElementById("error-modal").getElementsByClassName("error_content")[0].innerHTML = "Tệp đã chọn không phải là hình ảnh";
                                    setTimeout("$('#error-modal').fadeOut()", 2000);
                                }
                                else {
                                    var file_data = document.getElementById('img_add_news').files[0];
                                    if (file_data == null) return; // chưa chọn file
                                    var form_data = new FormData();
                                    form_data.append("img_add_news", file_data);
                                    $.ajax({
                                        url: '../ajax/asp/news/upload_avatar.aspx',
                                        data: form_data,
                                        processData: false,
                                        contentType: false,
                                        type: 'POST',
                                        success: function (data) {
                                            //$("#divTreeView").html(data);
                                        }
                                    });
                                    $.post("../ajax/asp/news/add_News_detail.aspx", { "cate": cate, "title": title.trim(), "review": review.trim(), "content": content.trim(), "source": source.trim(), "tags": tags.trim(), "img": img, "show": show, "top": top });
                                    sleep(5000);
                                    var xhttp;
                                    xhttp = new XMLHttpRequest();
                                    xhttp.onreadystatechange = function () {
                                        if (xhttp.readyState == 4 && xhttp.status == 200) {
                                            var temp = document.getElementById("news_list").innerHTML;
                                            document.getElementById("news_list").innerHTML = xhttp.responseText;
                                            document.getElementById("news_list").innerHTML += temp;
                                            $(".newslinks").click(function () {
                                                var newslinks = document.getElementsByClassName("newslinks");
                                                for (var j = 0; j < newslinks.length; j++) {
                                                    newslinks[j].className = newslinks[j].className.replace(" w3-leftbar w3-border-teal", "");
                                                }
                                                $(this).addClass(" w3-leftbar w3-border-teal");
                                            });
                                        }
                                    };
                                    xhttp.open("GET", "../ajax/asp/news/get_new_news.aspx?cate=" + cate, true);
                                    xhttp.send();
                                    document.getElementById("success-modal").style.display = "block";
                                    document.getElementById("success-modal").getElementsByClassName("success_content")[0].innerHTML = "Đã lưu thành công";
                                    setTimeout("$('#success-modal').fadeOut()", 2000);
                                    document.getElementById("news_detail_area").style.display = "none";
                                }
                            }
                        }
                    }

                });
                //tiny-mce
                tinymce.remove('textarea');
                tinymce.init({
                    selector: 'textarea#txt_news_content',
                    height: 180,
                    width: '83%',
                    plugins: [
                      'advlist autolink lists link image charmap print preview anchor',
                      'searchreplace visualblocks code fullscreen furigana ',
                      'insertdatetime media table contextmenu paste code',
                      'textcolor'
                    ],
                    fontsize_formats: "8px 10px 12px 14px 15px 16px 18px 20px 21px 22px",
                    toolbar: 'fontsizeselect insertfile undo redo | styleselect | bold italic | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image furigana'

                });
            }
        };
        xhttp.open("GET", "../ajax/asp/news/add_news_detail_form.aspx", true);
        xhttp.send();
    });
    $("#btn_accept_del_news").click(function () {
        var id = document.getElementById("del_news_id").innerHTML;
        $.post("../ajax/asp/news/del_news.aspx", { "id": id });
        $(".news" + id).remove();
        document.getElementById("xoabaiviet").style.display = "none";
        document.getElementById("news_detail_area").style.display = "none";
    });
    $("#btn_search").click(function () {
        var keyword = document.getElementById("txt_keyword").value;
        if(keyword.trim()!="")
            location.href="/tim-kiem/tu-khoa?keyword=" + keyword.trim() + "&page=1";
    });
});